package com.hyphenate.easeim.common.repositories

import androidx.lifecycle.MutableLiveData
import com.hyphenate.EMValueCallBack
import com.hyphenate.easeim.common.db.UserRepository
import com.hyphenate.easeim.common.db.UserRepository.getEaseUsers
import com.hyphenate.easeim.common.interfaceOrImplement.ResultCallBack
import com.hyphenate.easeim.common.net.ErrorCode
import com.hyphenate.easeui.domain.EaseUser
import com.hyphenate.exceptions.HyphenateException
import java.util.ArrayList
import java.util.Collections
import java.util.Comparator

/**
 * Time:5/8/21 6:45 PM
 * Author:
 * Description:
 */
open class EMContactManagerRepositoryKt : BaseEMRepository() {
    private val contactsRet: MutableLiveData<MutableList<EaseUser>> = MutableLiveData()

    /**
     * 获取联系人列表
     */
    fun fetchContacts(): MutableLiveData<MutableList<EaseUser>> {
        getContactLists(object : ResultCallBack<List<EaseUser>>() {
            override fun onError(error: Int, errorMsg: String) {}
            override fun onSuccess(value: List<EaseUser>) {
                contactsRet.postValue(value as MutableList<EaseUser>)
            }
        })
        return contactsRet
    }

    /**
     * 获取联系人列表
     * @param callBack
     */
    fun getContactLists(callBack: ResultCallBack<List<EaseUser>>?) {
        if (!isLoggedIn) {
            callBack?.onError(ErrorCode.EM_NOT_LOGIN)
            return
        }
        runOnIOThread {
            try {
                val usernames: MutableList<String> = ArrayList()
                usernames.addAll(contactManager.allContactsFromServer)
                usernames.addAll(contactManager.selfIdsOnOtherPlatform)
                getEaseUsers(usernames,
                    object : EMValueCallBack<List<EaseUser>> {
                        override fun onSuccess(easeUsers: List<EaseUser>) {
                            try {
                                updateBlackListFromServer(easeUsers)
                                sortData(easeUsers)
                                callBack?.onSuccess(easeUsers)
                            } catch (e: Exception) {
                                e.printStackTrace()
                            }
                        }

                        override fun onError(error: Int, errorMsg: String) {
                            callBack?.onError(error, errorMsg)
                        }
                    })
            } catch (e: HyphenateException) {
                e.printStackTrace()
                callBack?.onError(e.errorCode, e.description)
            }
        }
    }

    /**
     * 更新黑名单列表
     */
    private fun updateBlackListFromServer(easeUsers: List<EaseUser>) {
        if (easeUsers.isNotEmpty()) {
            val blackListFromServer = contactManager.blackListFromServer
            for (user in easeUsers) {
                if (blackListFromServer != null && blackListFromServer.isNotEmpty()) {
                    if (blackListFromServer.contains(user.username)) {
                        user.contact = 1
                        UserRepository.updateContact(user.contact, user.username)
                    }
                }
            }
        }
    }

    fun sortData(data: List<EaseUser>?) {
        if (data == null || data.isEmpty()) {
            return
        }
        Collections.sort(data, object : Comparator<EaseUser> {
            override fun compare(lhs: EaseUser, rhs: EaseUser): Int {
                return if (lhs.initialLetter == rhs.initialLetter) {
                    lhs.nickname.compareTo(rhs.nickname)
                } else {
                    if ("#" == lhs.initialLetter) {
                        return 1
                    } else if ("#" == rhs.initialLetter) {
                        return -1
                    }
                    lhs.initialLetter.compareTo(rhs.initialLetter)
                }
            }
        })
    }
}